package org.cg;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.SwingUtilities;
import org.apache.log4j.PropertyConfigurator;
import org.cg.gestor.Gestores;
import com.jogamp.opengl.util.Animator;

public class RunCoelhos {
	
	private final static String TITLE = "Coelhos e Cenouras";
	//private final static int FPS = 60;
	private final static int CANVAS_WIDTH = 640;
	private final static int CANVAS_HEIGHT = 480;
	
	private static Frame frame;
	private static Animator animator;
	private static GLCanvas canvas;

	public static void main (String[] args) {
		startWorld(args);
		
		//configurar o logger
		PropertyConfigurator.configure("src/properties/log4j.properties");
		
		startFrame();
	}
	
	private static void startWorld(String[] args) {
		//validacoes
		if (args == null || "".equals(args)) {
			//TODO sair graciosamente
			return;
		}
		if (args[0] == null || "".equals(args[0])) {
			//TODO sair graciosamente
			return;
		}
				
		//inicializar um mundo
		try {
			Gestores.inicializar(args[0]);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static void startFrame() {
		SwingUtilities.invokeLater(new Runnable() {
	    	public void run() {
	    		//profile
	    		GLProfile glp = GLProfile.getDefault();
	    		GLProfile.initSingleton();
	    		
	    		//capabilities
	    		GLCapabilities caps = new GLCapabilities(glp);
	    		caps.setDoubleBuffered( true );
	    		caps.setHardwareAccelerated( true );
	    		
	    		//gl canvas
	    	    canvas = new GLCanvas(caps);
	    	    CoelhosEventListener eventListener = new CoelhosEventListener();
	    	    canvas.addGLEventListener(eventListener);
	    	    canvas.addMouseMotionListener(eventListener);
	    	    canvas.addMouseListener(eventListener);
	    	    canvas.addMouseWheelListener(eventListener);
	    	    canvas.addKeyListener(eventListener);
	    	    
	    	    //ui frame
	    	    frame = new Frame();
	    	    frame.addWindowListener(new WindowAdapter() {
	                public void windowClosing(WindowEvent e) {
	                    System.exit(0);
	                }
	            });
	    	    frame.setSize(CANVAS_WIDTH,CANVAS_HEIGHT);
	    	    frame.add(canvas);
	    	    frame.setTitle(TITLE);
	    		frame.setVisible(true);

	    	    // Start animator
	    		animator = new Animator(canvas);
	            animator.start();
	    	}
	    });
	}
}
